/*===========================================================================
  Copyright (C) 2013-2014 by the Okapi Framework contributors
-----------------------------------------------------------------------------
  This library is free software; you can redistribute it and/or modify it 
  under the terms of the GNU Lesser General Public License as published by 
  the Free Software Foundation; either version 2.1 of the License, or (at 
  your option) any later version.

  This library is distributed in the hope that it will be useful, but 
  WITHOUT ANY WARRANTY; without even the implied warranty of 
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
  General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License 
  along with this library; if not, write to the Free Software Foundation, 
  Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

  See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/

package net.sf.okapi.lib.xliff2.reader;

import java.util.ArrayList;
import java.util.List;

import javax.xml.namespace.QName;

/**
 * Represent the module elements and attributes at a given extension point.
 * This is used for validating modules.
 */
class AllowedModules {

	private final List<String> attributes;
	private final List<ElementInfo> elements;
	
	private class ElementInfo {
		
		String qString;
		boolean zeroOrMore;
		int count;
		
		ElementInfo (String qString, boolean zeroOrMore) {
			this.qString = qString;
			this.zeroOrMore = zeroOrMore;
		}
	}

	public AllowedModules () {
		attributes = new ArrayList<String>();
		elements = new ArrayList<ElementInfo>();
	}

	public void addAttribute (String qString) {
		attributes.add(qString);
	}

	public void addElement (String qString,
		boolean zeroOrMore)
	{
		elements.add(new ElementInfo(qString, zeroOrMore));
	}

	public int isAllowedAttribute (QName qName) {
		return attributes.contains(qName.toString()) ? LocationValidator.ALLOWED : LocationValidator.NOT_ALLOWED;
	}

	public int isAllowedElement (QName qName) {
		// Get or create the counter for the given element
		for ( ElementInfo info : elements ) {
			if ( info.qString.equals(qName.toString()) ) {
				info.count++;
				if (( info.count > 1 ) && !info.zeroOrMore ) {
					return LocationValidator.TOO_MANY; // Not allowed because occurring too many times
				}
				return LocationValidator.ALLOWED; // Allowed
			}
		}
		return LocationValidator.NOT_ALLOWED; // Not allowed
	}
	
	/**
	 * Resets the counters for each elements allowed in the context.
	 */
	public void reset () {
		for ( ElementInfo info : elements ) {
			info.count = 0;
		}
	}

}
